import time
import signal
import sys
from gpiozero import DigitalOutputDevice

# ===== 用户可配置参数 =====
WDI_PIN = 25             # 看门狗输入引脚 (GPIO25)
FEED_INTERVAL_MS = 1000   # 喂狗间隔(毫秒)
# =========================

def delay_ms(ms):
    """毫秒级延时函数"""
    time.sleep(ms / 1000.0)

def signal_handler(sig, frame):
    """处理退出信号"""
    print("\n程序终止，清理资源...")
    wdi_device.close()
    sys.exit(0)

def feed_watchdog():
    """执行喂狗操作并打印状态"""
    wdi_device.on()   # 产生上升沿
    print(f"GPIO{WDI_PIN} 状态: {wdi_device.value} (上升沿)")
    
    # 短暂保持高电平形成脉冲
    delay_ms(10)
    
    wdi_device.off()  # 产生下降沿
    print(f"GPIO{WDI_PIN} 状态: {wdi_device.value} (下降沿)")
    print("喂狗成功")

if __name__ == "__main__":
    # 注册信号处理
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    print(f"启动看门狗喂狗程序 (GPIO{WDI_PIN}, 间隔: {FEED_INTERVAL_MS}ms)")
    print("按 Ctrl+C 停止程序")
    
    # 初始化GPIO设备
    wdi_device = DigitalOutputDevice(WDI_PIN, initial_value=False)
    print(f"初始状态: GPIO{WDI_PIN} = {wdi_device.value}")
    
    try:
        # 主循环
        while True:
            start_time = time.monotonic()
            
            feed_watchdog()  # 执行喂狗
            
            # 计算并等待剩余时间
            elapsed_ms = (time.monotonic() - start_time) * 1000
            remaining_ms = FEED_INTERVAL_MS - elapsed_ms
            
            if remaining_ms > 0:
                delay_ms(remaining_ms)
            else:
                print(f"警告! 喂狗周期超时 {-remaining_ms:.2f}ms")
                
    except Exception as e:
        print(f"发生错误: {str(e)}")
    finally:
        wdi_device.close()